package com.elysia.newsservice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elysia.newsservice.domain.dto.GameStatisticDTO;
import com.elysia.newsservice.domain.entity.GameStatistic;
import com.elysia.newsservice.domain.vo.GameStatisticVO;
import com.elysia.newsservice.mapper.GameStatisticMapper;
import com.elysia.newsservice.result.Result;
import com.elysia.newsservice.service.IGameStatisticService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 统计项服务实现类
 **/
@RequiredArgsConstructor
@Service
@Slf4j
public class IGameStatisticServiceImpl extends ServiceImpl<GameStatisticMapper, GameStatistic> implements IGameStatisticService {
    /**
     * 获取所有统计项
     * @return 全部统计项列表
     */
    @Override
    public Result<List<GameStatisticVO>> getAllGameStatistic() {
        List<GameStatisticVO> result = new ArrayList<>();
        List<GameStatistic> gameStatisticList = list();
        for (GameStatistic gameStatistic : gameStatisticList) {
            result.add(GameStatisticVO.builder().id(gameStatistic.getId()).label(gameStatistic.getLabel()).value(gameStatistic.getValue()).build());
        }
        return Result.success(result);
    }
    /**
     * 添加统计项
     * @param gameStatisticDTO 添加的统计项信息
     * @return 添加成功后的统计项信息
     */
    @Override
    public Result<GameStatisticVO> addGameStatistic(GameStatisticDTO gameStatisticDTO) {
        // 校验统计项是否重复
        if (lambdaQuery().eq(GameStatistic::getLabel, gameStatisticDTO.getLabel()).count() > 0)
            throw new IllegalArgumentException("统计项已存在");
        GameStatistic gameStatistic = GameStatistic.builder().label(gameStatisticDTO.getLabel()).value(gameStatisticDTO.getValue()).build();
        save(gameStatistic);
        return Result.success(GameStatisticVO.builder().id(gameStatistic.getId()).label(gameStatistic.getLabel()).value(gameStatistic.getValue()).build());
    }

    @Override
    public Result<GameStatisticVO> updateGameStatistic(Long id, GameStatisticDTO gameStatisticDTO) {
        // 获取原有的统计项数据
        GameStatistic gameStatistic = lambdaQuery().eq(GameStatistic::getId , id).one();
        // 判断是否修改了标签值
        if (!Objects.equals(gameStatistic.getLabel(), gameStatisticDTO.getLabel())) {
            // 判断统计项是否重复
            if (lambdaQuery().eq(GameStatistic::getLabel, gameStatisticDTO.getLabel()).count() > 0)
                throw new IllegalArgumentException("统计项已存在");
            gameStatistic.setLabel(gameStatisticDTO.getLabel());
        }
        gameStatistic.setValue(gameStatisticDTO.getValue());
        updateById(gameStatistic);
        return Result.success(GameStatisticVO.builder().id(gameStatistic.getId()).label(gameStatistic.getLabel()).value(gameStatistic.getValue()).build());
    }
}
